package com.liug.droidsmall2.utils.encryption;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class MD5 {
	/**
	 * MD5编码
	 * 
	 * @param sText
	 *            原始文本
	 * @param sCharsetName
	 *            编码名称
	 */
	public static String Encode(String sText, String sCharsetName) throws Exception {
		String s = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		sCharsetName = sCharsetName == null || sCharsetName.equals("") ? "UTF-8" : sCharsetName;
		byte[] source = sText.getBytes(sCharsetName);
		java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
		md.update(source);
		byte tmp[] = md.digest();
		char str[] = new char[16 * 2];
		int k = 0;
		for (int i = 0; i < 16; i++) {
			byte byte0 = tmp[i];
			str[k++] = hexDigits[byte0 >>> 4 & 0xf];
			str[k++] = hexDigits[byte0 & 0xf];
		}
		s = new String(str);
		// log.info("MD5原串=" + sText + ",加密串=" + s);
		return s.toLowerCase();
	}

	public static String getSign(String data, String securityKey, String charSet) throws Exception {
		String da = getSignStr(getMap(data));
		String charset = (charSet == null || charSet.equals("")) ? "UTF-8" : charSet;
		String str = MD5.Encode(da + securityKey, charset);
		return str;
	}

	public static String getSignStr(Map data) {
		List<String> list = new ArrayList<String>(data.keySet());
		Collections.sort(list, new Comparator() {
			public int compare(Object o1, Object o2) {
				return ((String) o1).compareTo(((String) o2));
			}
		});
		StringBuffer sb = new StringBuffer();
		for (String key : list) {
			sb.append(data.get(key));
		}
		String str = sb.toString();
		return str;
	}

	public static Map<String, Object> getMap(String jsonString) {
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(jsonString);
			@SuppressWarnings("unchecked")
            Iterator<String> keyIter = jsonObject.keys();
			String key;
			Object value;
			Map<String, Object> valueMap = new HashMap<String, Object>();
			while (keyIter.hasNext()) {
				key = (String) keyIter.next();
				value = jsonObject.get(key);
				valueMap.put(key, value);
			}
			return valueMap;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	/**
	 * 转换byte到16进制
	 * 
	 * @param b
	 *            要转换的byte
	 * @return 16进制格式
	 */
	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	/**
	 * 转换字节数组为16进制字串
	 * 
	 * @param b
	 *            字节数组
	 * @return 16进制字串
	 */
	public static String byteArrayToHexString(byte[] b) {
		StringBuilder resultSb = new StringBuilder();
		for (byte aB : b) {
			resultSb.append(byteToHexString(aB));
		}
		return resultSb.toString();
	}

	/**
	 * MD5编码
	 * 
	 * @param origin
	 *            原始字符串
	 * @return 经过MD5加密之后的结果
	 */
	public static String MD5Encode(String origin) {
		String resultString = null;
		try {
			resultString = origin;
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultString;
	}
}
